<template>
  <div>
    <el-container>
      <el-header
        style="
          background-color: #687581;
          height: 60px;
          color: #fff;
          font-size: 30px;
        "
        >充电桩信息
      </el-header>
    </el-container>

    <el-container>
      <el-aside width="200px">
        <el-menu
          default-active="1-1"
          class="el-menu-vertical-demo"
          @open="handleOpen"
          @close="handleClose"
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b"
        >
          <el-menu-item index="1">
            <el-menu-item index="1">
              <i class="el-icon-more"></i>
              <span slot="title" @click="toInfo">车辆信息</span>
            </el-menu-item>
          </el-menu-item>

          <el-menu-item index="2">
            <i class="el-icon-s-data"></i>
            <span slot="title" @click="toStatistic"> 车辆统计 </span>
          </el-menu-item>

          <el-menu-item index="3">
            <i class="el-icon-location"></i>
            <span slot="title">充电桩信息</span>
          </el-menu-item>

     

          <!-- <el-menu-item index="4">
            <i class="el-icon-monitor"></i>
            <span slot="title">车辆数量管理</span>
          </el-menu-item> -->
        </el-menu>
      </el-aside>

      <el-container>
        <div style="margin-top: 10px"></div>
        <el-header style="text-align: right; font-size: 12px">
          <div style="width: 500px"></div>
        </el-header>

        <div style="height: 628px">
          <el-table
            stripe
            max-height="550"
            :data="tableData"
            border
            @cell-dblclick="editCell"
            @cell-click="cellClick"
          >
            <el-table-column fixed prop="id" label="序号" width="250">
            </el-table-column>

            <el-table-column prop="state" label="使用状态" width="300">
              <template slot-scope="scope">
                <div v-if="row === scope.row.id && col === scope.column.id">
                  <el-input
                    placeholder=""
                    v-model="scope.row.state"
                    @blur="updateData"
                  ></el-input>
                </div>
                <div v-else>
                  {{ scope.row.state }}
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="num" label="充电位数量" width="300">
              <template slot-scope="scope">
                <div v-if="row === scope.row.id && col === scope.column.id">
                  <el-input
                    placeholder=""
                    v-model="scope.row.num"
                    @blur="updateData"
                  ></el-input>
                </div>
                <div v-else>
                  {{ scope.row.num }}
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="area" label="面积(平方米)" width="300">
            </el-table-column>

            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="success"
                  @click="openEdit(scope.$index, scope.row)"
                  >保存</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="openDel(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

       
          <div style="position: relative; left: 350px; top: 25px; width: 500px">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage3"
              :page-size="10"
              layout="prev, pager, next, jumper"
              :total="this.total"
          
            >
            </el-pagination>
          </div>
        </div>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import * as turf from "@turf/turf";
export default {
  data() {

    return {
     
      dialogVisible: false,
      row: "",
      col: "",
      tmpRow: "",
  
      tableData: [],
 
     
      value: "",
      currentPage3: 1,
   
     
      total: 0,
    
    };
  },

  watch: {

  },

  methods: {
    toInfo() {
      let { href } = this.$router.resolve({
        path: "/iteminfo",
      });
      window.open(href, "_blank");
    },
    toStatistic() {
      let { href } = this.$router.resolve({
        path: "/statistic",
      });

      window.open(href, "_blank");
    },

    search() {},

    // //查询
    toFilterData() {
      // 当用户没有输入内容就按enter键时，就return，不做任何操作，不去搜索
      if (this.input === "") {
        return;
      } else {
        if (this.EbikePage) {
          this.$axios({
            method: "get",
            url: `/searchSharedEBike?no=${this.input}`,
          }).then((res) => {
            if (res.data) {
              this.tableData = [];
              this.total = 0;

              const info = res.data;
              const item = {
                // id: index + 1 + (val - 1) * 10,
                id: info.sebId,
                no: info.no,
                state: info.state,
                color: info.color || "无",
                battery: info.battery || "无",
                position: `${info.lng}` + "," + `${info.lat}`,
                cumlative_usage_time: info.cumlativeUsageTime || "无",
                monthly_usage_times: info.monthlyUsageTimes,
              };

              this.tableData.push(item);
            } else {
              this.searchError();
            }
          });
        } else if (this.bikePage) {
          this.$axios({
            method: "get",
            url: `/searchSharedBike?no=${this.input}`,
          }).then((res) => {
            if (res.data) {
              this.tableData = [];
              this.total2 = 0;

              const info = res.data;
              const item = {
                // id: index + 1 + (val - 1) * 10,
                id: info.sbId,
                no: info.no,
                state: info.state,
                color: info.color || "无",
                battery: info.battery || "无",
                position: `${info.lng}` + "," + `${info.lat}`,
                cumlative_usage_time: info.cumlativeUsageTime || "无",
                monthly_usage_times: info.monthlyUsageTimes,
              };

              this.tableData.push(item);
            } else {
              this.searchError();
            }
          });
        } else if (this.personalEbikePage) {
          this.$axios({
            method: "get",
            url: `/searchPersonalEBike?no=${this.input}`,
          }).then((res) => {
            console.log(res);
            if (res.data) {
              this.tableData2 = [];
              this.total3 = 0;

              const info = res.data;
              const item = {
                pebId: info.pebId,

                no: info.no,
                ownership: info.ownership,
                timeInterval: info.timeInterval,
                campus: info.campus,
                color: info.color,
              };

              this.tableData2.push(item);
            } else {
              this.searchError();
            }
          });
        }
      }
    },

    searchError() {
      this.$message({
        type: "error",
        message: `没有找到该车辆`,
      });
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert("submit!");
          this.$message({
            message: "添加成功",
            type: "success",
          });

          this.onSubmit();
          this.dialogVisible = false;
        } else {
          // console.log("error submit!!");
          this.$message.error("信息有误");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleClose1(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    onSubmit() {
      const newItem = {
        no: this.form.no,
        ownership: this.form.user,
        timeInterval: this.form.timeInterval,
        campus: this.form.campus,
        color: this.form.color,
      };

      this.tableData2.push(newItem);

      this.$axios({
        method: "post",
        url: `/addPersonalEBike?no=${this.form.no}&ownership=${this.form.user}&timeInteravl=${this.form.timeInterval}&campus=${this.form.campus}&color=${this.form.color}`,
        data: newItem,
      }).then((res) => {
        console.log(res);
        if (res.status === 200) {
          this.$message({
            type: "success",
            message: `添加成功`,
          });
        }
      });
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },

    getItems(method, url, val) {
      this.$axios({
        method: method,
        url: url,
      }).then((res) => {

          console.log(res.data);
        this.tableData = [];

     
          this.getCGPNum();
          let cgpPosition = [];
          for (let index = 0; index < res.data.length; index++) {
            cgpPosition = [];
            const info = res.data[index];

            const p = info.locality.split(";");

            for (let index = 0; index < p.length; index++) {
              if (p[index]) {
                cgpPosition.push([
                  p[index].split(" ")[0],
                  p[index].split(" ")[1],
                ]);
              }
            }

            cgpPosition.push([cgpPosition[0][0], cgpPosition[0][1]]);

            var polygon = turf.polygon([cgpPosition]);

            var area = turf.area(polygon);

            let cgpArea = Math.floor(area);

            const item = {
              id: info.cpId,
              state: info.state,
              num: info.num,
              area: cgpArea,
            };

            this.tableData.push(item);
          }
        
      });
    },

    getPersonalEbikeItems(val) {
      this.$axios({
        method: "get",
        url: `/personalEBike/pageRecords?current=${val}`,
      }).then((res) => {
        this.tableData2 = [];

        for (let index = 0; index < res.data.length; index++) {
          const info = res.data[index];

          const item = {
            // id: index + 1 + (val - 1) * 10,
            pebId: info.pebId,

            no: info.no,
            ownership: info.ownership,
            timeInterval: info.timeInterval,
            campus: info.campus,
            color: info.color,
          };

          this.tableData2.push(item);
        }
      });
    },

    //电动车
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      //共享电动车分页

      if (this.value == "unavailable") {
        this.getItems("get", `getUnavailableEbike?page=${val}`, val);
      } else if (this.value == "logout") {
        this.getItems("get", `getLogoutEbike?page=${val}`, val);
      } else {
        this.getItems("get", `/chargingPile/pageRecords?current=${this.currentPage3}`, val);
      }
    },

    //单车
    handleSizeChange2(val) {
      console.log(`每页 ${val} 条`);
    },

    handleCurrentChange2(val) {
      // 共享单车分页
      this.getItems("get", `/sharedBike/pageRecords?current=${val}`, val);
    },

    handleSizeChange3(val) {
      console.log(`每页 ${val} 条`);
    },

    handleCurrentChange3(val) {
      this.getPersonalEbikeItems(val);
    },

    //更新车辆信息
    openEdit(index, row) {
      this.$confirm("是否确认更改该车辆信息？", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      })
        .then(() => {
          this.handleEdit(index, row);
          this.$message({
            type: "success",
            message: "更新成功",
          });
        })
        .catch((action) => {});
    },

    openDel(index, row) {
      this.$confirm("是否确认删除该车辆信息？", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      })
        .then(() => {
          this.handleDelete(index, row);
          this.$message({
            type: "success",
            message: "删除成功",
          });
        })
        .catch((action) => {});
    },

    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },

    handleEdit(index, row) {
      console.log(row);
      const data = {
        cpId: row.id,
        state: row.state,
        num:row.num
      };

     
      
        this.$axios({
          method: "post",
          url: `/updateChargingPile?cpId=${row.id}&state=${row.state}&num=${row.num}`,
          data: data,
        }).then((res) => {
          console.log(res);
        });
      
  
    },

    handleDelete(index, row) {

   
        this.$axios({
          method: "get",
          url: `/deleteChargingPile?cpId=${row.id}`,
        }).then((res) => {
          for (let index = 0; index < this.tableData.length; index++) {
            if (this.tableData[index].id == row.id) {
              this.tableData.splice(index, 1);
            }
          }
        });
      
    },

    editCell: function (row, column) {
      this.row = row.id;
      this.col = column.id;
      this.tmpRow = row;
      this.tmpRow.id = row.id;
    },

    editCell2: function (row2, column2) {
      this.row2 = row2.id;
      this.col2 = column2.id;
      this.tmpRow2 = row2;
      this.tmpRow2.id = row2.id;
    },

    updateData() {
      console.log(this.tmpRow.id);
      console.log(this.tmpRow.no);
      console.log(this.tmpRow.state);
      console.log(this.tmpRow.color);
    },

    cellClick() {
      // this.row = -1;
    },

    cellClick2() {},

    getAllSharedEbike() {
      this.$axios({
        method: "get",
        url: "getAllSharedEbike",
      }).then((res) => {
        // console.log(res.data);

        for (let index = 0; index < res.data.length; index++) {
          // console.log(res.data[index].color);
          const info = res.data[index];

          const item = {
            id: index + 1,
            no: info.no,
            state: info.state,
            color: info.color,
            battery: info.battery,
            position: `${info.lng}` + "," + `${info.lat}`,
            cumlative_usage_time: info.cumlative_usage_time,
            monthly_usage_times: info.monthly_usage_times,
          };

          this.tableData.push(item);
        }
      });
    },

    //getEbike
    get1stPageChargingPiles() {
      this.getItems(
        "get",
        `/chargingPile/pageRecords?current=${this.currentPage3}`,
        1
      );
    },

    getSharedEbikeByPage(val) {
      //分页查询
      this.$axios({
        method: "get",
        // url: `getSharedEbikeByPage?page=${val}`,
        url: `/sharedEBike/pageRecords?current=${val}`,
      }).then((res) => {
        // console.log(res.data.data);

        this.tableData = [];

        for (let index = 0; index < res.data.data.length; index++) {
          const info = res.data.data[index];

          const item = {
            id: index + 1 + (val - 1) * 10,
            no: info.no,
            state: info.state,
            color: info.color,
            battery: info.battery,
            position: `${info.lng}` + "," + `${info.lat}`,
            cumlative_usage_time: info.cumlative_usage_time,
            monthly_usage_times: info.monthly_usage_times,
          };

          this.tableData.push(item);
        }
      });
    },

    //getBike
    get1stPageSharedBike() {
      // this.getItems("get", `getSharedBikeByPage?page=${this.currentPage4}`, 1);
      this.getItems(
        "get",
        `/sharedBike/pageRecords?current=${this.currentPage4}`,
        1
      );
    },

    get1stPagePersonalEBike() {
      this.getPersonalEBikeNum();
      this.getPersonalEbikeItems(this.currentPage5);
    },

    getCGPNum() {
      this.$axios({
        method: "get",
        url: "/getChargingPileNum",
      }).then((res) => {
        this.total = res.data;
      });
    },
  },

  mounted() {
    this.get1stPageChargingPiles();
  },
};
</script>

<style>
.el-header {
  background-color: #687581;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #687581;
  color: #333;
  text-align: center;
  line-height: 200px;
  margin-right: 12px;
}

.el-main {
  /* height: 650px; */
}
</style>